from datetime import datetime
from tanxi.client.Handler.Logger import log_info
# from tanxi.models.sqlite.sqlite_article_model import ArticleModel

from django.conf import settings
if settings.DATABASE_TYPE == 'mysql':
    from tanxi.models.mysql.mysql_user_model import UserModel, UserManager 
    from tanxi.models.mysql.mysql_article_model import ArticleModel
        
elif settings.DATABASE_TYPE == 'sqlite':
    from tanxi.models.sqlite.sqlite_user_model import SqliteUserModel as UserModel
    from tanxi.models.sqlite.sqlite_user_model import SqliteUserManager as UserManager
    from tanxi.models.sqlite.sqlite_article_model import SqliteArticleModel as ArticleModel
else:
    raise ValueError("Unsupported database type specified in settings.")


from ...Handler.Logger import log_info
from django.db.models import F
from django.utils import timezone
from django.core.exceptions import ObjectDoesNotExist


class ArticleQueryHandler:
    def query_articles(self,id=None,title=None, author_id=None, is_published=None):
        """
        查询文章，根据标题、作者和发布状态进行过滤。
        """
        # articles = ArticleModel.objects.all()
        articles = ArticleModel.objects.annotate(
            author_name=F('author__name')  # 使用双下划线访问关联模型的字段
        ).values(
            'id', 'title', 'content','author_name',"author_id", 'is_published' ,"publish_time","tags" # 选择需要的字段
        )
        if id:
            id = int(id)
            log_info(f"文章id {id}")
            articles = articles.filter(id=id)

        if title:
            articles = articles.filter(title__icontains=title)
        
        if author_id:
            articles = articles.filter(author__name__icontains=author_id)
        
        if is_published is not None:
            articles = articles.filter(is_published=is_published)
        
        # # 根据外键 访问作者名字
        # update_articles = []
        # for article in articles:
      
        #     author_name = article.author.name
        #     # 将文章对象转换为字典
        #     article_dict = {
        #         "id": article.id,
        #         "title": article.title,
        #         "content":article.content,
        #         "author_id": author_name,  # 更新后的 author_id
        #         "is_published": article.is_published,
        #     }
        #     update_articles.append(article_dict)

        # log_info(f"返回文章 {update_articles}")
        # return update_articles
        return articles

class ArticleUpdateHandler:
    def update_or_create_article(self, article_data):
        """
        更新或创建文章。如果文章存在，则更新提供的字段；如果不存在，则创建新文章。
        :param article_data: 包含文章数据的字典
        :return: dict 返回操作结果，包括 article_id
        """
        if not article_data:
            raise ValueError("文章数据不能为空。")

        article_id = article_data.get('id')  # 前端可能传 'id' 或 'article_id'

        if article_id:
            try:
                # 尝试获取现有文章
                article = ArticleModel.objects.get(id=article_id)
                log_info(f"更新现有文章: ID={article_id}, 数据={article_data}")

                # 更新现有文章的字段
                for field, value in article_data.items():
                    if hasattr(article, field) and field != 'id':  # 排除 id 字段
                        setattr(article, field, value)
                article.updated_time = timezone.now()  # 更新时间戳
                article.save()
                return {'article_id': article.id, 'message': '文章更新成功'}

            except ObjectDoesNotExist:
                raise ValueError(f"文章 ID {article_id} 不存在。")
            except Exception as e:
                log_info(f"更新文章失败: {e}")
                raise ValueError(f"更新文章失败: {str(e)}")

        # 创建新文章
        log_info(f"创建新文章: 数据={article_data}")

        # 检查是否提供了 author_id（新文章必须提供 author_id）
        if 'author_id' not in article_data:
            raise ValueError("创建新文章时必须提供 author_id。")

        # 设置默认值
        defaults = {
            'title': '',
            'content': '',
            'is_published': False,
            'publish_time': timezone.now(),
            'read_count': 0,
            'tags': [],
            'updated_time': timezone.now()
        }
        defaults.update(article_data)
        defaults.pop('id', None)  # 移除 id，让 ORM 处理自增

        # 创建新文章
        try:
            article = ArticleModel.objects.create(**defaults)
            return {'article_id': article.id, 'message': '文章创建成功'}
        except Exception as e:
            log_info(f"创建文章失败: {e}")
            raise ValueError(f"创建文章失败: {str(e)}")
        
    def delete_article(self, id):
        """
        删除文章
        """
        ArticleModel.objects.filter(id=id).delete()
        return True
    